<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox, ElTag, ElImage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import * as admin from '@/api/index.js'
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

// 个人信息
const userInfo = ref({});

// 学生信息列表
const students = ref([]);

// 控制弹窗
const showEditUserDialog = ref(false);
const showEditStudentDialog = ref(false);
const addModel = ref(false);
// 当前编辑的学生
const currentStudent = ref(null);

const updateUser = ref({
  id: '',
  nickname: "",
  email: "",
  phone: "",
  password: "",
  img: "",
});

const addStuData = ref({
  parentId: '',
  name: '',
  age: '',
  gender: '',
  img: '',
});

// 编辑个人信息
const openEditUserDialog = () => {
  console.log(userInfo.value.id);
  updateUser.value.id = userInfo.value.id;
  updateUser.value.nickname = userInfo.value.nickname;
  updateUser.value.email = userInfo.value.email;
  updateUser.value.phone = userInfo.value.phone;
  updateUser.value.password = userInfo.value.password;
  updateUser.value.img = userInfo.value.img;
  showEditUserDialog.value = true;
};

// 提交个人信息修改
const submitUserInfo = () => {
  const res = admin.updateUser(updateUser.value);
  if (res.code == 0) {
    ElMessage.success("个人信息修改成功！");
    showEditUserDialog.value = false;
    finduser();
    findstu();
  }
};

// 头像上传
const handleAvatarUpload = (result) => {
  currentStudent.value.img = result.data;
};

// 添加/编辑学生信息
const openEditStudentDialog = (student = null) => {
  currentStudent.value = student
    ? { ...student }
    : { id: Date.now(), photo: "", name: "", age: "", gender: "男" };
    console.log(currentStudent.value);
  showEditStudentDialog.value = true;
};


// 提交学生信息
const submitStudentInfo = async () => {
  if (!currentStudent.value.name || !currentStudent.value.age || !currentStudent.value.gender) {
    ElMessage.warning("请填写完整的学生信息！");
    return;
  }

  const index = students.value.findIndex((s) => s.id === currentStudent.value.id);
  console.log(index);
  console.log(currentStudent.value);
  const res = await admin.updateStu(currentStudent.value);
  if (res.code == 0) {
    ElMessage.success("学生信息提交成功！");
    showEditStudentDialog.value = false;
    findstu();
  }
  
};


const addStudent = async () => {
  if (!addStuData.value.name || !addStuData.value.age || !addStuData.value.gender) {
    ElMessage.warning("请填写完整的学生信息！");
    return;
  }
  console.log(addStuData.value);
  const res = await admin.addStu(addStuData.value)
  if (res.code == 0) {
    ElMessage.success("学生信息提交成功！");
    addModel.value = false
    findstu();
  }
};

// 删除学生
const deleteStudent = (id) => {
  const param = {
    id: id,
  };
  ElMessageBox.confirm('确认删除该学生？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await admin.delStu(param)
      if (res.code == 0) {
        finduser();
        findstu();
        ElMessage.success("学生信息删除成功！");
      }
    })
    .catch(() => ElMessage.info('取消删除'));
};

// 学生照片上传
const handleStudentPhotoUpload = (result) => {
  
  addStuData.value.img = result.data
};


const finduser = async () => {
  const res = await admin.getUserDate({
    currentPage: 1,
    token: tokenStore.token,
  });
  if (res.code == 0) {
    userInfo.value = res.data;
    addStuData.value.parentId = userInfo.value.id
  }
}

const findstu = async () => {
  const res = await admin.getStuDate({
    currentPage: 1,
    token: tokenStore.token,
  });
  if (res.code == 0) {
    students.value = res.data;
  }
}
const uploadSuccess = (result)=>{
    updateUser.value.img = result.data;
}

finduser();
findstu();
</script>

<template>
  <div class="container">
    <h2>👤 个人中心</h2>

    <!-- 个人信息 -->
    <el-card class="user-card">
      <div class="user-info">
        <el-avatar :size="80" :src="userInfo.img" />
        <div class="info">
          <p><strong>昵称：</strong>{{ userInfo.nickname }}</p>
          <p><strong>邮箱：</strong>{{ userInfo.email }}</p>
          <p><strong>手机号：</strong>{{ userInfo.phone }}</p>
          <el-button type="primary" @click="openEditUserDialog">编辑信息</el-button>
        </div>
      </div>
    </el-card>

    <!-- 学生信息管理 -->
    <el-card class="student-card">
      <div class="card-header">
        <h3>🎓 学生信息</h3>
        <el-button type="primary" @click="addModel=true">添加学生</el-button>
      </div>

      <el-table :data="students" border stripe>
        <el-table-column label="照片" width="100">
          <template #default="{ row }">
            <el-avatar :size="50" :src="row.img" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="gender" label="性别" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="openEditStudentDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteStudent(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 个人信息编辑弹窗 -->
    <el-dialog v-model="showEditUserDialog" title="编辑个人信息">
      <el-form label-width="80px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/upload/image"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess"
          >
            <el-avatar :size="80" :src="updateUser.img" />
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="updateUser.nickname" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="updateUser.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="updateUser.phone" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="updateUser.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditUserDialog = false">取消</el-button>
        <el-button type="primary" @click="submitUserInfo">提交</el-button>
      </template>
    </el-dialog>

    <!-- 学生信息编辑弹窗 -->
    <el-dialog v-model="showEditStudentDialog" title="学生信息">
      <el-form label-width="80px">
        <el-form-item label="照片">
          <el-upload
            class="photo-uploader"
            action="http://localhost:8080/upload/image"
            name="file"
            :show-file-list="false"
            :on-success="handleAvatarUpload"
          >
            <el-avatar :size="80" :src="currentStudent.img" />
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="currentStudent.name" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="currentStudent.age" type="number" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentStudent.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditStudentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitStudentInfo">提交</el-button>
      </template>
    </el-dialog>


    <el-dialog v-model="addModel" title="学生信息">
      <el-form label-width="80px">
        <el-form-item label="照片">
          <el-upload
            class="photo-uploader"
            action="http://localhost:8080/upload/image"
            name="file"
            :show-file-list="false"
            :on-success="handleStudentPhotoUpload"
          >
            <el-avatar :size="80" :src="addStuData.img " />
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="addStuData.name" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="addStuData.age" type="number" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="addStuData.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addModel = false">取消</el-button>
        <el-button type="primary" @click="addStudent">提交</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
.container {
  max-width: 900px;
  margin: auto;
  padding: 20px;
}

.user-card,
.student-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader,
.photo-uploader {
  cursor: pointer;
}
</style>
